import axios from 'axios';
const qs = require('qs');
import Cookies from 'js-cookie';
axios.defaults.withCredentials = true;
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
//axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
const base = "http://192.168.1.222:8092/api/";
//const base = "http://192.168.1.244:8092/api/";
//get
export const getData = (getUrl, globeVue) => {
	return Promise.race([
		new Promise((resolve, reject) => {
			axios.get(base + getUrl)
				.then((response) => {
					//登录状态
					if(response.data.state == 401) {
						Cookies.set('token', '');
						// 退出登录
						globeVue.$router.push({
							name: 'login'
						});
						resolve({
							state: 0,
							msg: "重新登陆"
						});
					} //无法进入
					else if(response.data.state != 200) {
						var timerOut = {
							"state": 0,
							"msg": response.data.msg
						}
						resolve(timerOut);
					} else {
						resolve(response.data);
					}
				})
				.catch((error) => {
					resolve({
						state: 0,
						msg: "网络错误，请联系管理员"
					});
				});
		}),
		new Promise((resolve, reject) => {
			var timerOut = {
				"state": 0,
				"msg": "请求超时"
			}
			setTimeout(() => {
				resolve(timerOut);
			}, 50000);
		})
	])
}
//post
//globeVue 全局vue对象
export const postData = (postUrl, param, globeVue) => {

	return Promise.race([
		new Promise((resolve, reject) => {
			//每次调用接口必须带上systems字段名，例如systems:admin或systems:system
			axios.post(base + postUrl, qs.stringify(param))
				.then((response) => {
					//登录状态
					if(response.data.state == 401) {
						// 退出登录
						globeVue.$router.push({
							name: 'login'
						});
						resolve({
							state: 0,
							msg: "重新登陆"
						});
					}
					//无法进入
					else if(response.data.state != 200) {
						var timerOut = {
							"state": 0,
							"msg": response.data.msg
						}
						resolve(timerOut);
					} else {
						resolve(response.data);
					}
				})
				.catch((error, response) => {
					resolve({
						state: 0,
						msg: "网络错误，请联系管理员"
					});
				});
		}),
		new Promise((resolve, reject) => {
			var timerOut = {
				"state": 0,
				"msg": "请求超时" + postUrl
			}
			setTimeout(() => {
				resolve(timerOut);
			}, 50000);
		})
	])
}